package com.huifaapp.mall.activity.Homefragment;

import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.Specialactivity;
import com.huifaapp.mall.adapter.ChioAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.ChioBean;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.ShareUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.internal.Utils;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

//popuwindow下拉列表,属于组合式控件
public class ChioceActivity  extends AppCompatActivity {

    private XRecyclerView recyclerView;
    private List<ChioBean.DataBean.ListBean> listBeen;
    TextView mProductTv;  // 可以修改名称
    int curr;
    LinearLayout mProduct;

    TextView mSortTv;     // 可以修改名称

    LinearLayout mSort;

    TextView mActivityTv;   // 可以修改名称

    LinearLayout mActivity;

    ListView mSupplierListLv;

    //三个popuwindow所需的数据集合
    private ArrayList<Map<String, String>> mMenuData1;
    private ArrayList<Map<String, String>> mMenuData2;
    private ArrayList<Map<String,String>> mMenuData3;

    //popuwindow所用的listView,PopupWindow对象
    private ListView mPopListView;
    private PopupWindow mPopupMenu;
    //设置三个popuwindow下的同一个ListView所需的不同适配器
    private SimpleAdapter mMenuAdapter1;
    private SimpleAdapter mMenuAdapter2;
    private SimpleAdapter mMenuAdapter3;
    private ChioAdapter chioAdapter;
    private ImageView iv_share_chio_share;
    private static final int SHARET_WXHY = 517;
    //设置的一个标记,方便对点击不同LinearLayout做对应的操作
    private int menuIndex = 0;
    public static Map<Integer, Boolean> hmap;
    ArrayList<String> idlist = new ArrayList<>();
    private ImageView iv_assess_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chioce);
        hmap = new HashMap<>();
        initView();

        //ButterKnife的初始化
        ButterKnife.bind(this);
        //初始化Popuwindow显示的数据
        initData();
        //初始化popuwindow控件
        initPopMenu();
    }

    private void initView() {
        listBeen = new ArrayList<>();
        mActivity = (LinearLayout) findViewById(R.id.supplier_list_activity);
        mActivityTv = (TextView) findViewById(R.id.supplier_list_activity_tv);
        mProductTv = (TextView) findViewById(R.id.supplier_list_product_tv);
        mProduct = (LinearLayout) findViewById(R.id.supplier_list_product);
        mSortTv = (TextView) findViewById(R.id.supplier_list_sort_tv);
        mSort = (LinearLayout) findViewById(R.id.supplier_list_sort);
        mSupplierListLv = (ListView) findViewById(R.id.supplier_list_lv);
        recyclerView = (XRecyclerView) findViewById(R.id.chioce_recy);
        iv_share_chio_share= (ImageView) findViewById(R.id.iv_share_chio_share);
        iv_assess_back= (ImageView) findViewById(R.id.iv_assess_back);
        iv_assess_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        recyclerView.setLayoutManager(new GridLayoutManager((ChioceActivity.this), 2 ,GridLayoutManager.VERTICAL,false));
        chioAdapter = new ChioAdapter(ChioceActivity.this,listBeen);
        recyclerView.setAdapter(chioAdapter);

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                curr = 0;
                requestEmit("");
            }

            @Override
            public void onLoadMore() {
                curr++;
                requestEmit("");
            }
        });
        requestEmit("");

if(SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
    iv_share_chio_share.setVisibility(View.VISIBLE);
}else{
    iv_share_chio_share.setVisibility(View.GONE);
}

        iv_share_chio_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Contig.checkedIndexCHIO.size() == 0) {
                    Toast.makeText(ChioceActivity.this, "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < Contig.checkedIndexCHIO.size(); i++)
                        idlist.add(listBeen.get(Contig.checkedIndexCHIO.get(i)).getId());

                    Log.e("数据Toady", idlist + "-===========id");


                    StringBuffer permission = new StringBuffer();
                    for (int i = 0; i < idlist.size(); i++) {
                        if (i == 0) {
                            permission.append(idlist.get(i));
                        } else {
                            permission.append("," + idlist.get(i));
                        }
                        Contig.listididCHIO.add(idlist.get(i));

                    }
//                    LoadStoreList(0, 0, Contig.listidid);

                    ApiManager
                            .getInstance()
                            .getApiServer()
                            .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(ChioceActivity.this), permission.toString())
                            .compose(ApiManager.<ShareImageBean>handlResult())
                            .subscribe(new ObserverCallback<ShareImageBean>(ChioceActivity.this) {
                                @Override
                                protected void onSuccessful(ShareImageBean resp) {

                                    saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                                    if (Contig.checkedIndexCHIO.size() > 0) {
                                        for (int a = 0; a < Contig.checkedIndexCHIO.size(); a++) {
                                            Contig.ShareListCHIO.add(listBeen.get(Contig.checkedIndexCHIO.get(a)).getId());
                                        }
                                    }
                                    chioAdapter = new ChioAdapter(ChioceActivity.this,listBeen);
                                    recyclerView.setAdapter(chioAdapter);

                                }

                                @Override
                                protected void onError(String code, String errMsg) {
                                    ToastUtils.showShortSafe(errMsg);
                                }
                            });
                    idlist.clear();
            }
            }
        });

    }
    private void saveImage(List<String> imageUrls, final String cconten, final int type) {

        Log.v("shiran", "------------saveImage------------");

        final LoadingDialog dialog = new LoadingDialog(ChioceActivity.this);
        dialog.setContent("正在生成图片请稍后");


        Observable.just(imageUrls)
                .map(new Function<List<String>, List<String>>() {

                    @Override
                    public List<String> apply(List<String> list) throws Exception {

                        List<String> paths = new ArrayList<String>();
                        for (String s : list) {
                            FutureTarget<File> future = Glide.with(APP.getInstance())
                                    .load(s)
                                    .downloadOnly(500, 500);
                            File cacheFile = future.get();
                            String uuid = UUID.randomUUID().toString();
                            FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                            String pat = savePath + uuid + ".jpg";
                            paths.add(pat);

                        }


                        return paths;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                    }

                    @Override
                    public void onNext(List<String> value) {
                        LogUtils.e(value);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }

                        switch (type) {
                            case SHARET_WXHY:


                                    ShareUtils.sharePicToFriendNoSDK(ChioceActivity.this, value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                break;
//                            case SHARET_WXPYQ:
//                                ShareUtils.share9PicsToWXCircle(getActivity(), "", value);
//                                break;
                            default:

                                break;
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }
                });

    }
    private void requestEmit(String orderType){
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"goods/list")
                .addParams("start",curr+"")
                .addParams("length",20+"")
                .addParams("orderType",orderType)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                    }
                    @Override
                    public void onResponse(String response) {
                        recyclerView.refreshComplete();
                        initData(response);

                    }
                });
    }

    private void initData(String response) {
//        Gson gson = new Gson();
//        ChioBean chioBean = gson.fromJson(response,ChioBean.class);
//        listBeen = chioBean.getData().getList();
//        ChioAdapter chioAdapter = new ChioAdapter(ChioceActivity.this,listBeen);
//        recyclerView.setAdapter(chioAdapter);
        Gson gson = new Gson();
        ChioBean babyBean = gson.fromJson(response,ChioBean.class);
        if (babyBean != null && babyBean.getData() != null && babyBean.getData().getList() != null) {
            if (curr == 0) {
                listBeen.clear();
            }
            listBeen.addAll(babyBean.getData().getList());
            chioAdapter.notifyDataSetChanged();
        } else {

        }

    }
    private void initData() {

        mMenuData1 = new ArrayList<>();
        //存放String的字符串数组
        String[] menuStr1 = new String[]{"综合排序", "价格由高到低", "价格由低到高"
                };
        //创建一个小盒子,放编号和值
        Map<String, String> map1;
        for (int i = 0, len = menuStr1.length; i < len; ++i) {
            map1 = new HashMap<String, String>();
            map1.put("name", menuStr1[i]);
            mMenuData1.add(map1);
        }
        //创建一个存放popupwindow加载数据的大盒子2,Map集合(键,值)
        mMenuData2 = new ArrayList<>();
        String[] menuStr2 = new String[]{};
        Map<String, String> map2;
        for (int i = 0, len = menuStr2.length; i < len; ++i) {
            map2 = new HashMap<String, String>();
            map2.put("name", menuStr2[i]);
            mMenuData2.add(map2);
        }
        //创建一个存放popupwindow加载数据的大盒子3,Map集合(键,值)
        mMenuData3 = new ArrayList<>();
        String[] menuStr3 = new String[]{"红包由高到低", "红包由低到高"};
        Map<String, String> map3;
        for (int i = 0, len = menuStr3.length; i < len; ++i) {
            map3 = new HashMap<String, String>();
            map3.put("name", menuStr3[i]);
            mMenuData3.add(map3);
        }
    }

    //初始化popuwindow
    private void initPopMenu() {
        //把包裹的ListVIew的布局XML文件转换为VIew对象
        View popView = LayoutInflater.from(this).inflate(R.layout.popwin_supplier_list, null);
        //创建popuwindow对象,参数1popuwindow要显示的布局,参数2,3:定义popuwindow所占用的宽高
        mPopupMenu = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        //设置popuwindow外部可以点击              true:可以，      false:不可以
        mPopupMenu.setOutsideTouchable(true);
        //是popuwindow里填充的listView拥有焦点
        mPopupMenu.setFocusable(true);
        //如果想要让popuwindow具有一些操作,比如动画效果之类的,必须给popuwindow设置背景
        mPopupMenu.setBackgroundDrawable(new ColorDrawable());
        //设置popuwindow的动画效果
//        mPopupMenu.setAnimationStyle(R.style.popwin_anim_style);
        //设置popuwindow结束时的监听事件
        mPopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                //设置TextView的颜色,把所有LinearLayout的文本颜色该为灰色
                mProductTv.setTextColor(Color.parseColor("#5a5959"));
                mSortTv.setTextColor(Color.parseColor("#5a5959"));
                mActivityTv.setTextColor(Color.parseColor("#5a5959"));
            }
        });
        //点击popuwindow以外的区域,使popuwindow消失(实际就是让ListView下面的LinerLayout,设置点击事件)
        LinearLayout list_bottom= (LinearLayout) popView.findViewById(R.id.popwin_supplier_list_bottom);
        list_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //当LinerLayout被点击时,这popuwindow消失
                mPopupMenu.dismiss();
            }
        });

        //获取listVIew对象
        mPopListView = (ListView) popView.findViewById(R.id.popwin_supplier_list_lv);
        //点击popuwindow以外区域时,使popuwindow消失.在这里得到了ListView下面的LinearLayout,设置监听事件
/*SimpleAdapter 简单数据适配器:正好有一组数据,是Map集合放到ArrayList集合,就可以使用这个适配器了,不是太常用,设置数据太麻烦.
context:上下文    data:设置所有条目的数据,一个ArrayList大集合(包含所有条目信息),里面又有一个map集合(通过map来设置一个条目的数据)
resource:引用布局资源(可以引用复杂的布局.xml文件,区别于ArrayAdapter)
from:String数组,装map条目内容的键            to:int数组,装控件id  二者具有映射关系,代表对应的内容放到对应的位置*//*
ArrayList<Map<String,Object>> data=new ArrayList<Map<String,Object>>();
        //注意:一个map,代表一条item的数据.
        Map<String,Object> map=new HashMap<String, Object>();
        ListView对象.setAdapter(new SimpleAdapter(context, data, resource, from, to));*/
        //创建SimpleAdapter,一个listView安卓原生封装的适配器
        mMenuAdapter1 = new SimpleAdapter(this, mMenuData1,
                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});
        mSort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestEmit("totalSalesDesc");
            }
        });

//        mMenuAdapter2 = new SimpleAdapter(this, mMenuData2,
//                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});

        mMenuAdapter3 = new SimpleAdapter(this, mMenuData3,
                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});

        //设置Popuwindow里的listView点击事件,当点击listVIew里的一个item时,把这个item数据显示到最上方
        mPopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long ld) {
                //首先让Popuwindow消失
                mPopupMenu.dismiss();
                //设置一个标识,以方便做对应LinerLayout的点击事件.
                switch (menuIndex) {
                    case 0:
                        //获取点击对应条目的文本数据
                        String currentProduct = mMenuData1.get(position).get("name");
                        //把文本数据设置到原始布局里的文本
                        if (currentProduct.equals("价格由高到低")){
                            requestEmit("priceDesc");
                        }if (currentProduct.equals("价格由低到高")){
                                 requestEmit("priceAsc");
                    }

                        mProductTv.setText(currentProduct);
                        break;
                    case 2:
                        String currentAct = mMenuData3.get(position).get("name");
                        mActivityTv.setText(currentAct);
                        if (currentAct.equals("红包由高到低")){
                            requestEmit("commissionDesc");
                        }if (currentAct.equals("红包由低到高")){
                        requestEmit("commissionAsc");
                    }
                        requestEmit(currentAct);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    //三个Popuwindow所依附的LinearLayout,设置点击事件,也就是三个LinearLayout具备了点击事件
    @OnClick({ R.id.supplier_list_product,R.id.supplier_list_sort,R.id.supplier_list_activity })
    public void onClick(View view){
        switch (view.getId()) {
            //第一个Popuwindow所执行的点击后的逻辑
            case R.id.supplier_list_product:
                //设置其TextView点击时为绿色
                mProductTv.setTextColor(Color.parseColor("#ff2040"));
                //设置Popuwindow里的ListView适配器
                mPopListView.setAdapter(mMenuAdapter1);
//                if (Build.VERSION.SDK_INT == 24) {
//                    int[] location = new int[2];
//                    mProduct.getLocationOnScreen(location);
//                    mPopupMenu.showAtLocation(getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, location[1]);
//                    mPopupMenu.update();
//                } else {
//                    mPopupMenu.showAsDropDown(mProduct, 0, -50);
//                }
//                int[] location = new int[2];
//                mProduct.getLocationOnScreen(location);
                //让Popuwindow显示出来.  参数1:VIew对象,决定了在哪个控件下显示,  参数2决定了Popuwindow的坐标,X轴,Y轴
                mPopupMenu.showAsDropDown(mProduct);
                //显示在下方
//                mPopupMenu.showAtLocation(mProduct, Gravity.NO_GRAVITY,location[0]+mProduct.getWidth(),location[1]);
                menuIndex=0;
                break;
            //第2个Popuwindow所执行的点击后的逻辑
            case R.id.supplier_list_sort:
//                mSortTv.setTextColor(Color.parseColor("#39ac69"));
//                mPopListView.setAdapter(mMenuAdapter2);
//                mPopupMenu.showAsDropDown(mSort);
                mSortTv.setTextColor(Color.parseColor("#ff2040"));
                menuIndex=1;
                break;
            //第3个Popuwindow所执行的点击后的逻辑
            case R.id.supplier_list_activity:
                mActivityTv.setTextColor(Color.parseColor("#ff2040"));
                mPopListView.setAdapter(mMenuAdapter3);
                mPopupMenu.showAsDropDown(mActivity);
                menuIndex=2;
                break;

            default:
                break;
        }
    }


///**
// *  在android7.0上，如果不主动约束PopuWindow的大小，比如，设置布局大小为 MATCH_PARENT,那么PopuWindow会变得尽可能大，以至于 view下方无空间完全显示PopuWindow，而且view又无法向上滚动，此时PopuWindow会主动上移位置，直到可以显示完全。
// *　解决办法：主动约束PopuWindow的内容大小，重写showAsDropDown方法：
// * @param anchor
// */
//@Override
//public void showAsDropDown(View anchor) {
//    if(Build.VERSION.SDK_INT == 24) {
//        Rect rect = new Rect();
//        anchor.getGlobalVisibleRect(rect);
//        int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
//        setHeight(h);
//    }
//    super.showAsDropDown(anchor);
//}



}
